package com.woniu.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.woniu.domain.Company;
import com.woniu.domain.Position;
import com.woniu.service.CompanyService;
import com.woniu.service.PositionService;
import com.woniu.service.ResumeService;
import com.woniu.vo.DataPie;
import com.woniu.vo.PositionDetailsVo;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class CustomJob {
    @Resource
    private CompanyService companyService;

    @Resource
    private PositionService positionService;

    @Resource
    private ResumeService resumeService;

    @Resource
    private RedisTemplate redisTemplate;

    //自定义的定时任务内容
    @Scheduled(cron = "0 0/2 * * * ?")
    public void excute(){
        System.out.println("======开始定时任务======");
        //将company，position，resume的访问量更新到数据库中
        //查询redis中的数据
        ListOperations operations = redisTemplate.opsForList();
        List cAndp = operations.range("cAndp", 0, -1);
        //将其转换为ArrayList
        ArrayList<PositionDetailsVo> details = new ArrayList<>();
        for (Object o : cAndp) {
            String s = JSON.toJSONString(o);
            PositionDetailsVo rePosition= JSONObject.parseObject(s,PositionDetailsVo.class);
            details.add(rePosition);
        }
        //更新职位的访问量
        for (PositionDetailsVo positionDetailsVo : details) {
            Position position = new Position();
            position.setPositionId(positionDetailsVo.getPositionId());
            position.setVisitCount(positionDetailsVo.getPositionVisitCount());
            positionService.updateById(position);
        }

        //查询出所有公司
        List<Company> companies = companyService.list(null);
        for (Company company : companies) {
            //根据公司id查询出该公司所有的职位访问量
            List<DataPie> dataPies = positionService.queryPositionByCid(company.getCompanyId());
            if (!ObjectUtils.isEmpty(dataPies)) {
                Integer companyVC=0;
                //职位访问量相加为公司访问量
                for (DataPie pie : dataPies) {
                    companyVC=companyVC+pie.getValue();
                }
                company.setVisitCount(companyVC);
                //更新公司的访问量
                companyService.updateById(company);
            }
        }
    }
}
